package com.lwj.liwanjia.view.activity.supermarket;


import android.content.Intent;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lwj.liwanjia.MainActivity;
import com.lwj.liwanjia.R;
import com.lwj.liwanjia.adapter.MiaoshuAdapter;
import com.lwj.liwanjia.bean.AddGwcBean;
import com.lwj.liwanjia.bean.CollectBean;
import com.lwj.liwanjia.bean.ShangpinDetailBean;
import com.lwj.liwanjia.impl.AddGwcView;
import com.lwj.liwanjia.impl.CollectView;
import com.lwj.liwanjia.impl.ShangpinDetailView;
import com.lwj.liwanjia.presenter.AddGwcPresenter;
import com.lwj.liwanjia.presenter.CollectPresenter;
import com.lwj.liwanjia.presenter.ShangpinDetailPresenter;
import com.lwj.liwanjia.utils.GlideImageLoader;
import com.lwj.liwanjia.utils.ShareDialog;
import com.lwj.liwanjia.utils.SpBuyDialog;
import com.lwj.liwanjia.utils.SpfUtils;
import com.lwj.liwanjia.utils.ZFlowLayout;
import com.lwj.liwanjia.view.activity.dianpu.DianpuActivity;
import com.lwj.liwanjia.view.activity.login.LoginActivity;
import com.lwj.liwanjia.view.fragment.supermarket.MiaoShuFragment;
import com.lwj.liwanjia.view.fragment.supermarket.PingjiaFragment;
import com.superrecycleview.superlibrary.adapter.SuperBaseAdapter;
import com.superrecycleview.superlibrary.recycleview.SuperRecyclerView;
import com.umeng.socialize.UMShareAPI;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 商品详情
 */
public class ShangpinDetailActivity extends AppCompatActivity implements ShangpinDetailView, CollectView, AddGwcView {

    Unbinder unbinder;
    @BindView(R.id.shangpin_banner_detail)
    Banner shangpinBannerDetail;
    @BindView(R.id.tv_back)
    TextView tvBack;
    @BindView(R.id.toobar_title)
    TextView toobarTitle;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.collapse_layout)
    CollapsingToolbarLayout collapseLayout;
    @BindView(R.id.shangpin_detail_apb)
    AppBarLayout shangpinDetailApb;
    @BindView(R.id.tv_shangpin_name)
    TextView tvShangpinName;
    @BindView(R.id.btn_enter_shop)
    Button btnEnterShop;
    @BindView(R.id.shangpin_jianjie)
    TextView shangpinJianjie;
    @BindView(R.id.tv_shangpin_price)
    TextView tvShangpinPrice;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.tv_pingfen)
    TextView tvPingfen;
    @BindView(R.id.tv_youfei)
    TextView tvYoufei;
    @BindView(R.id.tv_xiaoshouliang)
    TextView tvXiaoshouliang;
    @BindView(R.id.tv_loaction)
    TextView tvLoaction;
    @BindView(R.id.shangpin_detail)
    RelativeLayout shangpinDetail;
    @BindView(R.id.ask_info)
    ZFlowLayout askInfo;
    @BindView(R.id.ask_layout)
    LinearLayout askLayout;
    @BindView(R.id.tv_miaoshu)
    TextView tvMiaoshu;
    @BindView(R.id.miaoshu_line)
    View miaoshuLine;
    @BindView(R.id.tv_pingjai)
    TextView tvPingjai;
    @BindView(R.id.pingjia_line)
    View pingjiaLine;
    @BindView(R.id.miaoshu_layout)
    LinearLayout miaoshuLayout;
    @BindView(R.id.textItem)
    TextView textItem;
    @BindView(R.id.activty_tongchengshangping)
    LinearLayout activtyTongchengshangping;
    @BindView(R.id.rl_tongcheng)
    SuperRecyclerView rlTongcheng;
    @BindView(R.id.ig_kefu)
    ImageView igKefu;
    @BindView(R.id.ig_tousu)
    ImageView igTousu;
    @BindView(R.id.ig_gouwuche)
    ImageView igGouwuche;
    @BindView(R.id.gouwuche_number)
    TextView gouwucheNumber;
    @BindView(R.id.gouwuche_frame)
    FrameLayout gouwucheFrame;
    @BindView(R.id.tv_add_gouwuce)
    TextView tvAddGouwuce;
    @BindView(R.id.tv_buy)
    TextView tvBuy;
    @BindView(R.id.shangpin_bottom1)
    LinearLayout shangpinBottom1;
    @BindView(R.id.progress)
    ProgressBar progress;
    @BindView(R.id.progress_bar)
    RelativeLayout progressBar;
    @BindView(R.id.coor)
    CoordinatorLayout coordinatorLayout;


    private List<String> imageList = new ArrayList<>();//轮播图
    private Fragment mFragment;
    private List<Fragment> fragments = new ArrayList<>();//评价，描述
    private MiaoshuAdapter adapter;//同城商品
    private List<ShangpinDetailBean.DataBean.LocalGoodsBean> otherlist = new ArrayList<>();
    private Window window;
    private ShangpinDetailPresenter detailPresenter;
    private CollectPresenter collectPresenter;//收藏
    private String token;
    private String shopGoodsCode;
    private String commodityType;
    private ArrayList<String> detailImages = new ArrayList<>();//商品详情描述
    private AddGwcPresenter addGwcPresenter;
    private SpfUtils spfUtils;
    private int shopInfoId;//店铺ID
    private SpBuyDialog dialog;
    private String goodsUrl;//分享的URL
    private String goodsName;//商品名
    private String goodsInfo;//商品描述
    private ShangpinDetailBean.DataBean.GoodsDetailsBean goodsDetails;
    private int imgHeight;//商品描述图片高度
    private int imgWidth;//商品描述图片宽度
    int widthPixels;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shangpin_detail);
        setStableTransparent(0);
        unbinder = ButterKnife.bind(this);
        //动态设置图片展示的高度
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        widthPixels = dm.widthPixels;
        shangpinDetailApb.setLayoutParams(new CoordinatorLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,widthPixels));
        initView();
        initData();
    }

    private void getFragments() {
        fragments.add(MiaoShuFragment.getInstance(detailImages, imgWidth, imgHeight));//商品描述
        fragments.add(PingjiaFragment.getInstance(shopGoodsCode, commodityType));//商品评价
        mFragment = fragments.get(0);
        getSupportFragmentManager().beginTransaction().add(R.id.fragment_container3, mFragment).commit();
    }

    private void initData() {
        if (shopGoodsCode != null) {
            detailPresenter.getShangpinDetail(token, shopGoodsCode, commodityType);
        }
    }

    private void initView() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            shopGoodsCode = bundle.getString("shopGoodsCode");
            commodityType = bundle.getString("commodityType");
            if (commodityType.equals("超市")) {
                tvBuy.setVisibility(View.GONE);
            }
        }
        GridLayoutManager manager = new GridLayoutManager(this, 2);
        rlTongcheng.setLayoutManager(manager);
        rlTongcheng.setRefreshEnabled(false);
        rlTongcheng.setLoadMoreEnabled(false);
        rlTongcheng.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.right = getResources().getDimensionPixelOffset(R.dimen.x10);
                outRect.bottom = getResources().getDimensionPixelOffset(R.dimen.x10);
                if (parent.getChildAdapterPosition(view) % 2 == 1) {
                    outRect.left = getResources().getDimensionPixelOffset(R.dimen.x10);
                }
            }
        });
        toolbar.inflateMenu(R.menu.collect);
        adapter = new MiaoshuAdapter(this, otherlist);
        rlTongcheng.setAdapter(adapter);
        detailPresenter = new ShangpinDetailPresenter(this);
        collectPresenter = new CollectPresenter(this);
        addGwcPresenter = new AddGwcPresenter(this);
        spfUtils = SpfUtils.getSpfUtils(this);
        token = spfUtils.getToken();
        gouwucheNumber.setText(spfUtils.getGwcNumber() + "");
        listener();
    }

    // 初始化标签
    @SuppressWarnings("ResourceType")
    private void initLabel(List<String> list) {
        ViewGroup.MarginLayoutParams lp = new ViewGroup.MarginLayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        lp.leftMargin = 20;
        lp.topMargin = 18;
        for (int i = 0; i < list.size(); i++) {
            final TextView tag = new TextView(this);
            Drawable drawable = getResources().getDrawable(R.mipmap.xuanze);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(),
                    drawable.getMinimumHeight());
            tag.setCompoundDrawables(drawable, null, null, null);
            tag.setCompoundDrawablePadding(10);
            tag.setText(list.get(i));
            tag.setTextColor(getResources().getColor(R.color.color3B3B3B));
            tag.setTextSize(16);
            askInfo.addView(tag, lp);
        }
    }

    private void listener() {
        //滑动监听
        shangpinDetailApb.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (verticalOffset < -(shangpinBannerDetail.getHeight() - widthPixels)) {
                    toobarTitle.setVisibility(View.VISIBLE);
                    setStableTransparent(1);
                } else {
                    toobarTitle.setVisibility(View.INVISIBLE);
                    setStableTransparent(0);
                }
            }
        });
        //收藏
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                if (item.getItemId() == R.id.collect) {
                    collectPresenter.getCollect(token, commodityType, shopGoodsCode);
                } else if (item.getItemId() == R.id.share) {
                    if (!TextUtils.isEmpty(goodsInfo) && !TextUtils.isEmpty(goodsName) && !TextUtils.isEmpty(goodsUrl)) {
                        ShareDialog dialog = new ShareDialog(ShangpinDetailActivity.this, goodsDetails.getSlideshowImg().get(0), goodsUrl, goodsName, goodsInfo);
                        dialog.show();
                    }
                }
                return false;
            }

        });
        //返回
        tvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //进入店铺
        btnEnterShop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ShangpinDetailActivity.this, DianpuActivity.class);
                intent.putExtra("shopInfoId", shopInfoId);
                startActivity(intent);
            }
        });

        //同城商品点击
        adapter.setOnItemClickListener(new SuperBaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, Object item, int position) {
                Intent intent = new Intent(ShangpinDetailActivity.this, ShangpinDetailActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("shopGoodsCode", otherlist.get(position).getCommodityCode());
                bundle.putString("commodityType", otherlist.get(position).getCommodityType());
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
        //商品描述
        tvMiaoshu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switchFragment(fragments.get(0));
                tvMiaoshu.setTextColor(getResources().getColor(R.color.colorEC921A));
                miaoshuLine.setVisibility(View.VISIBLE);
                tvPingjai.setTextColor(getResources().getColor(R.color.color747474));
                pingjiaLine.setVisibility(View.INVISIBLE);
            }
        });
        //商品评价
        tvPingjai.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switchFragment(fragments.get(1));
                tvMiaoshu.setTextColor(getResources().getColor(R.color.color747474));
                miaoshuLine.setVisibility(View.INVISIBLE);
                tvPingjai.setTextColor(getResources().getColor(R.color.colorEC921A));
                pingjiaLine.setVisibility(View.VISIBLE);
            }
        });
    }

    //修改状态栏
    public void setStableTransparent(int state) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            if (state == 0) {
                window.setStatusBarColor(0x00000000);
            } else {
                window.setStatusBarColor(getResources().getColor(R.color.colorEC921A));
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

    //Umeng分享回调
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        UMShareAPI.get(this).release();
        if (detailPresenter != null) {
            detailPresenter = null;
        }
        if (collectPresenter != null) {
            collectPresenter = null;
        }
        if (addGwcPresenter != null) {
            addGwcPresenter = null;
        }
        unbinder.unbind();
        super.onDestroy();
    }

    @OnClick({R.id.ig_kefu, R.id.ig_tousu, R.id.gouwuche_frame, R.id.tv_add_gouwuce, R.id.tv_buy})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ig_kefu://客服
//                Intent intent = new Intent(ShangpinDetailActivity.this, KefuActivity.class);
//                startActivity(intent);
                Toast.makeText(this, "暂未开通", Toast.LENGTH_SHORT).show();
                break;
            case R.id.ig_tousu://投诉
                Toast.makeText(this, "暂未开通", Toast.LENGTH_SHORT).show();
                break;
            case R.id.gouwuche_frame://进入购物车
                Intent intent1 = new Intent(ShangpinDetailActivity.this, MainActivity.class);
                intent1.putExtra("type", "购物车");
                startActivity(intent1);
                finish();
                break;
            case R.id.tv_add_gouwuce://加入购物车
                String activePrice = tvShangpinPrice.getText().toString().replace("￥", "");
                String price = activePrice.split("元")[0];
                if (commodityType.equals("超市")) {
                    addGwcPresenter.addGouWuChe(token, shopGoodsCode, commodityType, Double.parseDouble(price));
                } else if (commodityType.equals("商城")) {
                    dialog = new SpBuyDialog(this, shopGoodsCode, gouwucheNumber, "加入购物车", Double.parseDouble(price));
                    dialog.show();
                }
                break;
            case R.id.tv_buy://立即购买
                String activePrice1 = tvShangpinPrice.getText().toString().replace("￥", "");
                String price1 = activePrice1.split("元")[0];
                if (commodityType.equals("商城")) {
                    dialog = new SpBuyDialog(this, shopGoodsCode, gouwucheNumber, "立即购买", Double.parseDouble(price1));
                    dialog.show();
                }
                break;
        }
    }

    private void switchFragment(Fragment fragment) {
//        //判断当前显示的Fragment是否就是切换的Fragment
        if (mFragment != fragment) {
            //判断切换的fragment是否已经添加过
            if (!fragment.isAdded()) {
                getSupportFragmentManager().beginTransaction().hide(mFragment)
                        .add(R.id.fragment_container3, fragment).commit();
            } else {
                getSupportFragmentManager().beginTransaction().hide(mFragment)
                        .show(fragment).commit();
            }
            mFragment = fragment;
        }
    }

    @Override
    public void showProgress() {
        progressBar.setVisibility(View.VISIBLE);
    }

    @Override
    public void hideProgress() {
        progressBar.setVisibility(View.GONE);
    }

    @Override
    public void showError(Exception e) {
        Toast.makeText(this, "数据加载失败！", Toast.LENGTH_SHORT).show();
    }

    // 加入购物车
    @Override
    public void addGouWuChe(AddGwcBean addGwcBean) {
        if (addGwcBean.getState() == 0) {
            startActivity(new Intent(ShangpinDetailActivity.this, LoginActivity.class));
        } else if (addGwcBean.getState() == 1) {
            if (addGwcBean.isData()) {
                Toast.makeText(this, "加入购物车成功", Toast.LENGTH_SHORT).show();
                gouwucheNumber.setText((Integer.parseInt(gouwucheNumber.getText().toString()) + 1) + "");
            } else {
                Toast.makeText(this, "加入购物车失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    //    收藏
    @Override
    public void getCollect(CollectBean collectBean) {
        if (collectBean.getState() == 0) {
            Toast.makeText(this, "点击收藏失败！", Toast.LENGTH_SHORT).show();
        } else {
            if (collectBean.isData()) {//收藏
                toolbar.getMenu().findItem(R.id.collect).setIcon(R.mipmap.xihuan_xuanzhong);
            } else {//取消收藏
                toolbar.getMenu().findItem(R.id.collect).setIcon(R.mipmap.xihuan_weixuanzhong);
            }
        }
    }

    @Override
    public void getShangpinDetail(ShangpinDetailBean shangpinDetailBean) {
        if (shangpinDetailBean.getState() == 1) {
            coordinatorLayout.setVisibility(View.VISIBLE);
            ShangpinDetailBean.DataBean dataBean = shangpinDetailBean.getData().get(0);
            goodsUrl = dataBean.getGoodUrl();
            goodsDetails = dataBean.getGoodsDetails();
            goodsName = goodsDetails.getGoodsName();
            goodsInfo = goodsDetails.getGoodsDescribe();
            //轮播图
            bannerData(goodsDetails);
            //商品信息
            shangpinData(goodsDetails);
            //标签
            List<String> label = goodsDetails.getLabel();
            if (label != null && label.size() > 0) {
                initLabel(label);
            } else {
                askLayout.setVisibility(View.GONE);
            }
            //商品描述图片
            if (goodsDetails.getDetailsImg() != null && goodsDetails.getDetailsImg().size() > 0) {
                detailImages.addAll(goodsDetails.getDetailsImg());
            }
            imgHeight = dataBean.getImgHeight();
            imgWidth = dataBean.getImgWidth();
            getFragments();
            //同城商品
            otherlist.clear();
            if (dataBean.getLocalGoods().size() > 0) {
                otherlist.addAll(dataBean.getLocalGoods());
            }
            adapter.notifyDataSetChanged();
        }
    }

    /**
     * 商品信息
     *
     * @param goodsDetails
     */
    private void shangpinData(ShangpinDetailBean.DataBean.GoodsDetailsBean goodsDetails) {
        shopInfoId = goodsDetails.getShopInfoId();
        tvShangpinName.setText(goodsDetails.getGoodsName());//商品名
        shangpinJianjie.setText(goodsDetails.getGoodsDescribe());//商品描述
        tvShangpinPrice.setText("￥" + goodsDetails.getNowPrice());//当前价格
        tvPrice.setText("￥" + goodsDetails.getCommodityPrice());//原价
        tvPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        tvPingfen.setText(goodsDetails.getGrade() + "分");//评分
        tvYoufei.setText("邮费：" + goodsDetails.getPostage());//邮费
        tvXiaoshouliang.setText("销售量：" + goodsDetails.getSalesVolume());//销售量
        tvLoaction.setText(goodsDetails.getAddress());//地址
    }

    /**
     * 轮播图数据
     *
     * @param goodsDetails
     */
    private void bannerData(ShangpinDetailBean.DataBean.GoodsDetailsBean goodsDetails) {
        if (goodsDetails.getIsCollect() == 0) {//没有收藏
            toolbar.getMenu().findItem(R.id.collect).setIcon(R.mipmap.xihuan_weixuanzhong);
        } else if (goodsDetails.getIsCollect() == 1) {//收藏了
            toolbar.getMenu().findItem(R.id.collect).setIcon(R.mipmap.xihuan_xuanzhong);
        }
        toobarTitle.setText(goodsDetails.getGoodsName());
        if (goodsDetails.getSlideshowImg() != null && goodsDetails.getSlideshowImg().size() > 0) {
            imageList.addAll(goodsDetails.getSlideshowImg());
        }
        shangpinBannerDetail.setImages(imageList)
                .setImageLoader(new GlideImageLoader())
                .setBannerStyle(BannerConfig.NUM_INDICATOR)
                .setDelayTime(4000)
                .start();
    }


}
